const db = require('../Mysql/sql')
const dayjs = require('dayjs')
const configAll = require('../../configuration.js') //公共配置
const filterJson = (body, sqlObj) => {
	if (typeof body !== "object") return
	const q = Object.keys(body)
		.filter(key => sqlObj.includes(key))
		.reduce((obj, key) => {
			obj[key] = body[key];
			return obj;
		}, {});
	return q
}
const news = {
	//根据typeid获取文章
	getArticleListType(req, res) {
		let body = req.body

		let {
			pageSize,
			page,
			...obj
		} = body //过滤分页
		let len = Object.keys(obj).length
		pageSize = body.pageSize || 10
		page = page == 1 ? 0 : ((body.page - 1) * pageSize)

		let sql = `select count(*) as total from article,users where authorid=? and authorid = userid` //total
		let sql2 =
			`select * from article,users where users.userid = article.authorid and authorid=? order by pubdate desc limit ?,?`
		let arr = [obj.authorid]
		let sql3 =
			`select a.*,u.username,u.handimg FROM article a left join users u on a.authorid = u.userid where id=?`
		if (obj.typeid != 0) {
			sql =
				`select count(*) as total from article,users where typeid=? and authorid=? and authorid = userid` //total
			sql2 = `select a.*,u.username,u.handimg from article a left join users u on a.authorid=u.userid where 
			a.typeid in (?) and a.authorid=? order by pubdate desc limit ?,?`
			arr = [obj.typeid, obj.authorid]
		}
		db.query(sql, arr, (err, results) => {
			if (err) return res.cc(err)
			if (!results[0].total) return res.send({
				status: 200,
				msg: '获取成功',
				data: [],
				total: results[0].total
			})
			db.query(sql2, [...arr, page, pageSize], (err, results2) => {
				if (err) return res.cc(err)
				let promise = new Promise((resolve, reject) => {
					let state = results2.some(v => v.forwardid)
					state ? '' : reject()
					let j = 0
					for (let i = 0; i < results2.length; i++) {
						if (results2[i].forwardid) {
							j++
							db.query(sql3, [results2[i].forwardid], (err3, results3) => {
								results2[i].list = results3
								j--
								if (j === 0) {
									resolve()
								}
							})

						}
					}
				}).then(() => {
					res.send({
						status: 200,
						msg: '获取成功',
						data: results2,
						total: results[0].total
					})
				}).catch(() => {
					res.send({
						status: 200,
						msg: '获取成功',
						data: results2,
						total: results[0].total
					})
				})

			})
		})

	},
	//获取文章列表(根据authorid、用户id 获取)
	getArticleList(req, res) {
		let body = req.body
		let {
			pageSize,
			page
		} = body //过滤分页
		// 0 3 6 9
		pageSize = body.pageSize || 10
		page = page == 1 ? 0 : ((body.page - 1) * pageSize)
		let sql = `select count(*) as total from article,users where authorid = userid` //total
		//获取自己或者全部所有文章(userid)
		let sql2 = `select a.*,u.username,u.handimg
		${body.likerid?`,if((a.id,a.authorid) in (SELECT l.articleid as id,l.userid as authorid FROM like_list l where likerid = ${body.likerid}),true,false) as isdz`:''}
		from article a left join users u on a.authorid = u.userid 
		${body.userid?'where u.userid='+body.userid:''}
		${body.typeid?'where a.typeid='+body.typeid:''}
		${body.entryid?`where entryid regexp '(^|,)(${body.entryid})(,|$)' ` : '' }
		${body.searchValue?`and title like '%${body.searchValue}%' or content like '%${body.searchValue}%'`:''}
		order by a.pubdate desc limit ?,?`
		let sql3 =
			`select a.*,u.username,u.handimg FROM article a left join users u on a.authorid = u.userid where id=?`

		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			if (!results[0].total) return res.send({
				status: 200,
				msg: '获取成功',
				data: [],
				total: results[0].total
			})
			db.query(sql2, [page, pageSize], async (err, results2) => {
				if (err) return res.cc(err)
				let promise = new Promise((resolve, reject) => {
					let state = results2.some(v => v.forwardid)
					state ? '' : reject()
					let j = 0
					for (let i = 0; i < results2.length; i++) {
						if (results2[i].forwardid) {
							j++
							db.query(sql3, [results2[i].forwardid], (err3,
								results3) => {
								results2[i].list = results3
								j--
								if (j === 0) {
									resolve()
								}
							})

						}
					}
				}).then(() => {
					res.send({
						status: 200,
						msg: '获取成功',
						data: results2,
						total: results[0].total
					})
				}).catch(() => {
					res.send({
						status: 200,
						msg: '获取成功',
						data: results2,
						total: results[0].total
					})
				})
			})
		})

	},
	//根据id获取详情
	getArticleListId(req, res) {
		let body = req.body
		let sql = `select article.*,users.username,users.handimg,
		if(article.id in (select id from article a where authorid in (select u.userid from (select * from follow where fanid = ${body.userid}) f 
		right join users u on u.userid=f.userid where f.userid is null and u.userid!=${body.userid})),true,false) as isgz,
		if((article.id,article.authorid) in (SELECT l.articleid as id,l.userid as authorid FROM like_list l where likerid = ${body.userid}),true,false) as isdz 
		from article left join users on article.authorid=users.userid where article.id=?`
		let sql2 = 'update article set heat=? where id=?'
		const sql3 = `select count(*) as total from comment where articleid=${body.id}` //获取评论数量
		const sql5 = `select count(*) as total from article where forwardid=${body.id}` //获取转发数量
		let sql4 =
			`select a.*,u.username,u.handimg FROM article a left join users u on a.authorid = u.userid where id=?`

		db.query(sql, body.id, (err, results) => { //获取详情
			if (err) return res.cc(err)
			let heat = results[0].heat + 1
			db.query(sql2, [heat, body.id]) //更新热度
			db.query(sql3, [], (err3, results3) => {
				if (err3) return res.cc(err3)
				db.query(sql5, [], (err5, results5) => {
					if (err5) return res.cc(err5)
					let data = {
						...results[0],
						pl: results3[0].total,
						zf: results5[0].total
					}
					if (results.length) {
						data = {
							...data,
							followId: results[0].id
						}
					}
					let promise = new Promise((resolve, reject) => {
						let state = data.forwardid
						state ? '' : reject()
						if (data.forwardid) {
							db.query(sql4, [data.forwardid], (err4,
								results4) => {
								data.list = results4
								resolve()
							})

						}
					}).then(() => {

						res.send({
							status: 200,
							msg: '获取成功',
							data: data,
						})
					}).catch(() => {

						res.send({
							status: 200,
							msg: '获取成功',
							data: data,
						})
					})
				})
			})

		})

	},
	//新增文章
	addArticle(req, res) {
		//content video title img（文章内容，视频，标题，图片）
		let content = {
			...req.body,
			authorid: req.auth.userid,
			pubdate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
		}
		const sql = 'insert into article set ?'
		db.query(sql, content, (err, results) => {
			if (err) return res.cc(err)
			if (!results.affectedRows) return res.cc('新增失败')
			res.send({
				status: 200,
				mag: '新增成功',
				data: results.insertId
			})
		})
	},
	//删除文章
	delArticle(req, res) {
		// let content = req.body
		if (!req.body.id) return res.cc('id不能为空')
		const sql = 'delete from article where id=?'
		// const sql = 'update article set isdel=1 where id=?'
		db.query(sql, req.body.id, (err, results) => {
			if (err) return res.cc(err)
			if (!results.affectedRows) return res.cc('删除失败')
			res.cc('删除成功', 200)
		})

	},
	//根据文章id更新文章
	updataArticle(req, res) {
		let body = {
			updatetime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
			...req.body
		}
		const sql = 'update article set ? where id=?'
		db.query(sql, [req.body, req.body.id], (err, results) => {
			if (err) return res.cc(err)
			if (!results.affectedRows) return res.cc('更新成功')
			res.cc('更新成功', 200)
		})
	},
	//上传图片
	upload(req, res) {
		let {
			size,
			filename
		} = req.file
		let url = ['/article', '/headimg', '/cover_img', '/crowd_img', '/store_logo', '/goods_details', '/common']

		filename = `${configAll.baseUrl}${url[req.body.type || 0]}/${filename}`
		if (!req.body.type) { //上传文章
			let sql = `update article set img=?,imgSize=? where id=?`
			db.query(sql, [filename, size, req.body.id], (err, results) => {
				if (err) return res.cc(err)
				if (!results.affectedRows) res.cc('上传失败')
				res.send({
					status: 200,
					msg: '上传成功',
					data: {
						url: filename,
						size: size
					}
				})
			})
		} else if (req.body.type == 1) { //上传头像
			let sql = `update users set handimg=? where userid=${req.auth.userid}`
			db.query(sql, [filename], (err, results) => {
				if (err) return res.cc(err)
				if (!results.affectedRows) res.cc('上传失败')
				res.send({
					status: 200,
					msg: '上传成功',
					data: {
						url: filename,
						size: size
					}
				})
			})
		} else if (req.body.type == 2) { //直播封面上传
			res.cc('上传成功', 200, {
				url: filename,
				size: size
			})
		} else if (req.body.type == 3) { //上传群封面
			let sql = `update crowd set img=? where id=${req.body.id} and leaderid=${req.auth.userid}`
			db.query(sql, [filename], (err, results) => {
				if (err) return res.cc(err)
				if (!results.affectedRows) res.cc('上传失败')
				res.cc('上传成功', 200, {
					url: filename,
					size: size
				})
			})
		} else if (req.body.type == 4) { //店铺logo
			let sql = `update store set logo=? where userid = ${req.auth.userid} and id=${req.body.id}`
			db.query(sql, [filename], (err, results) => {
				if (err) return res.cc(err)
				if (!results.affectedRows) res.cc('上传失败')
				res.cc('上传成功', 200, {
					url: filename,
					size: size
				})
			})
		} else if (req.body.type == 5) { //商品详情图
			res.cc('上传成功', 200, {
				url: filename,
				size: size
			})
		} else if (req.body.type == 6) { //商品详情图
			const sql = `update dictionary set img=? where id=${req.body.id}`
			db.query(sql, [filename], (err, results) => {
				if (err) return res.cc(err)
				if (!results.affectedRows) res.cc('上传失败')
				res.cc('上传成功', 200, {
					url: filename,
					size: size
				})
			})
		}
	},
	//视频
	uploadVideo(req, res) {
		let {
			id
		} = req.body
		let {
			size,
			filename
		} = req.file
		const sql = `update article set video=?,videoSize=? where id=?`
		filename = `${configAll.baseUrl}/article/${filename}`
		db.query(sql, [filename, size, id], (err, results) => {
			if (err) return res.cc(err)
			if (!results.affectedRows) res.cc('上传失败')
			res.send({
				status: 200,
				msg: '上传成功',
				data: {
					url: filename,
					size: size
				}
			})
		})
	},
	uploadTwo(req, res) {
		let {
			size,
			filename
		} = req.file
		res.send({
			status: 200,
			msg: '上传成功',
			data: {
				url: filename,
				size: size
			}
		})
	},
	//获取文章hot榜
	getArticleListHot(req, res) {
		let {
			hot
		} = req.body

		const sql = `select a.*,u.username,u.handimg
		${req.body.likerid?`,if((a.id,a.authorid) in (SELECT l.articleid as id,l.userid as authorid FROM like_list l where likerid = ${req.body.likerid}),true,false) as isdz`:''} 
		from article a,users u where a.authorid=u.userid
		${req.body.typeid?'and a.typeid='+req.body.typeid:''}
		${req.body.searchValue?`and a.title like '%${req.body.searchValue}%' or a.content like '%${req.body.searchValue}%'`:''}
		order by heat desc limit ?`
		let sql3 =
			`select a.*,u.username,u.handimg FROM article a left join users u on a.authorid = u.userid where id=?`
		db.query(sql, hot, (err, results) => {
			if (err) return res.cc(err)
			let promise = new Promise((resolve, reject) => {
				let state = results.some(v => v.forwardid)
				state ? '' : reject()
				let j = 0
				for (let i = 0; i < results.length; i++) {
					if (results[i].forwardid) {
						j++
						db.query(sql3, [results[i].forwardid], (err3, results2) => {
							results[i].list = results2
							j--
							if (j === 0) {
								resolve()
							}

						})

					}
				}
			}).then(() => {
				res.send({
					status: 200,
					msg: '获取成功',
					data: results
				})
			}).catch(() => {
				res.send({
					status: 200,
					msg: '获取成功',
					data: results
				})
			})

		})
	},

	//获取关注列表文章
	getFollowArticleList(req, res) {
		let sql =
			`select a.*,u.username,u.handimg
		${req.body.likerid?`,if((a.id,a.authorid) in (SELECT l.articleid as id,l.userid as authorid FROM like_list l where likerid = ${req.body.likerid}),true,false) as isdz`:''}
		from article a,users u where a.authorid = u.userid and a.authorid 
		in (select u.userid from (select * from follow where fanid = ${req.auth.userid}) f left join users u on u.userid=f.userid) order by a.pubdate desc`
		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			res.send({
				status: 200,
				msg: '获取成功',
				data: results
			})
		})
	},

	//点赞(点赞人likerid，artileid文章id)
	giveLike(req, res) {
		let body = {
			articleid: req.body.articleid,
			likerid: req.auth.userid,
			userid: req.body.userid
		}

		let sql = `SELECT * FROM like_list where articleid = ? and likerid=?`
		let sql2 = `insert into like_list set ?`
		let sql3 = `delete from like_list where id=? and likerid=?`
		db.query(sql, [body.articleid, body.likerid], (err, results) => {
			if (err) return res.cc(err)
			if (!results.length) {
				db.query(sql2, body, (err2, results2) => {
					if (err2) return res.cc(err2)
					res.cc('点赞成功', 200)
				})
			} else {
				db.query(sql3, [results[0].id, body.likerid], (err2, results2) => {
					if (err2) return res.cc(err2)
					res.cc('取消成功', 200)
				})
			}

		})
	},
	//根据用户获取点赞表
	getUserLike(req, res) {
		const sql = `SELECT lk.*,u.username,u.handimg,a.*,
		if((a.id,a.authorid) in (SELECT l.articleid as id,l.userid as authorid FROM like_list l where likerid = ${req.auth.userid}),true,false) as isdz
		FROM like_list lk left join users u on lk.userid = u.userid
		left join article a on a.id = lk.articleid where lk.likerid = ${req.auth.userid}`
		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			res.send({
				status: 200,
				msg: '获取成功',
				data: results
			})
		})
	}
}

const arrayToTree = (arr, parent_id = 'parent_id', id = 'id') => {
	const treeView = []
	// 初始化匹配map
	const vMap = arr.reduce((m, item) => {
		item.children = []
		m[item.id] = item
		return m
	}, {})
	for (let i = 0; i < arr.length; i++) {
		if (vMap[arr[i][parent_id]]) {
			vMap[arr[i][parent_id]].children.push(arr[i])
			vMap[arr[i][parent_id]].children = vMap[arr[i][parent_id]].children.sort((a, b) => a.id - b.id)
		} else {
			treeView.push(arr[i])
		}
	}
	return treeView.sort((a, b) => a.id - b.id)
}
const comment = {
	//根据文章id获取评论
	getCommentListId(req, res) {
		const {
			articleid,
			parent_id
		} = req.body
		let sql =
			`select c.*,u.username,u.handimg,
			if((select count(*) from comment ac where ac.parent_id = c.id)>0,1,0) as is_child
			from comment c,users u where c.reviewerid = u.userid and articleid=? and parent_id=?`
		db.query(sql, [articleid, parent_id], (err, results) => {
			if (err) return res.cc(err)
			res.send({
				status: 200,
				msg: '获取成功',
				data: results
			})
		})

	},
	//根据用户id获取评论
	getUserCommentListId(req, res) {
		const sql =
			`SELECT c.id as comment_id,c.content as comment_content,c.createtime,c.reviewerid,c.type,c.replyid,c.parent_id,c.level,c.authorid as comment_authorid,a.*,u.username,u.handimg
			FROM comment c left join article a on c.articleid = a.id left join users u on c.authorid = u.userid where c.reviewerid = ${req.auth.userid}`
		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			res.send({
				status: 200,
				msg: '获取成功',
				data: results
			})
		})
	},
	//根据用户id和文章id生成评论 createtime
	createCommentInfo(req, res) {
		let body = {
			...req.body,
			reviewerid: req.auth.userid,
			createtime: dayjs().format('YYYY-MM-DD HH:mm:ss')
		}
		let sql = `insert into comment set ?`
		db.query(sql, body, (err, results) => {
			if (err) return res.cc(err)
			res.send({
				status: 200,
				data: results.insertId,
				msg: '评论成功'
			})
		})
	},
	//根据用户id、文章id、评论id 删除评论
	delCommentListId(req, res) {
		let {
			id
		} = req.body
		let sql = `delete from comment where id=? and reviewerid=${req.auth.userid}`
		db.query(sql, id, (err, results) => {
			if (err) return res.cc(err)
			res.cc('删除成功', 200)
		})
	}
}

const entry = {
	getEntryList(req, res) {
		let body = req.body
		let {
			pageSize,
			page
		} = body //过滤分页
		pageSize = body.pageSize || 10
		page = page == 1 ? 0 : ((body.page - 1) * pageSize)
		let sql = `select e.*,u.username,u.handimg from entry e,users u where e.creatorid = u.userid
		${body.type == -1 ? '': `and e.type=${body.type || 0}`} and e.title like '%${body.searchValue}%'
		${body.id?`and e.id=${body.id} `:''}
		order by e.readimg_num desc limit ?,?
		`
		const sql2 = `update entry set readimg_num = readimg_num+1 where id=${body.id}`
		db.query(sql, [page, pageSize], (err, results) => {
			if (err) return res.cc(err)
			if (body.id) {
				db.query(sql2, [], () => {
					res.cc('获取成功', 200, results)
				})
			} else {
				res.cc('获取成功', 200, results)
			}
		})
	},
	//创建词条publish_num
	createEntry(req, res) {
		let body = {
			...req.body,
			creatorid: req.auth.userid,
			createtime: dayjs().format('YYYY-MM-DD HH:mm:ss')
		}

		//判断是否重复词条
		let sql = `select * from entry where title=?`
		let sql2 = `insert into entry set ?`
		let sql3 = `update entry set publish_num=publish_num+1 where type=?`
		db.query(sql, [body.title], (err, results) => {
			if (err) return res.cc(err)
			if (!results.length) {
				db.query(sql2, body, (err2, results2) => {
					if (err) return res.cc(err2)
					if (!results2) return res.cc('创建失败')
					res.cc('创建成功', 200, results2.insertId)
				})
			} else {
				
				db.query(sql3, [body.type], (err2, results2) => {
					if (err) return res.cc(err2)
					if (!results2) return res.cc('创建失败')
					res.cc('已存在词条', 200, results[0].id)
				})
			}

		})
	}
}
module.exports = {
	...news,
	...comment,
	...entry
}